<template>
  <div>
    <template>
      <div>
        <!--        <el-input v-model="url" type="text" style="width: 20%" /> &nbsp; &nbsp;-->
        form: <el-image style="width: 100px; height: 100px;border-radius:50%;" :src="fromUser.img_http" fit="fill" />
        <br />
        to: <el-image style="width: 100px; height: 100px;border-radius:50%;" :src="toUser.img_http" fit="fill" />
        <div class="flex_row">
          <el-card class="box-card" style="height: 300px">
            <ul class="infinite-list" style="overflow:auto;height:300px" v-infinite-scroll="load">
              <li v-for="(item, i) in userSocketInfo" class="infinite-list-item">
                <div :class="item.type === 'right' ? 'right message my_message' : 'left message frnd_message'"
                  v-show="item.body !== ''">
                  <div v-if="item.type === 'left'">
                    <el-image style="width: 50px; height: 50px;border-radius:50%;margin: 15px"
                      :src="item.type === 'right' ? fromUser.img_http : toUser.img_http" fit="fill" />
                  </div>
                  <div class="flex_column">
                    <div style="font-max-size: 1em">{{ item.type === 'right' ? fromUser.nick_name : toUser.nick_name }}
                    </div>
                    <div>
                      <p>{{ item.body }}</p>
                    </div>
                  </div>
                  <div v-if="item.type === 'right'">
                    <el-image style="width: 50px; height: 50px;border-radius:50%;margin: 10px"
                      :src="item.type === 'right' ? fromUser.img_http : toUser.img_http" fit="fill" />
                  </div>
                </div>
              </li>
            </ul>
          </el-card>
        </div>
        <el-form ref="form" :model="socketMsg" label-width="80px">
          <!--          <el-form-item label="user_id">-->
          <!--            <el-input type="text" v-model="socketMsg.user_id"></el-input>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="form">-->
          <!--            <el-input type="text" v-model="socketMsg.from"></el-input>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="to">-->
          <!--            <el-input type="text" v-model="socketMsg.to"></el-input>-->
          <!--          </el-form-item>-->
          <el-form-item label="msg">
            <el-input type="textarea" v-model="socketMsg.msg" :rows="5" />
          </el-form-item>
          <el-form-item>
            <el-button type="info" @click="send">发送消息</el-button>
            <el-button @click="initWebsocket" type="primary">连接</el-button>
            <el-button @click="exit" type="danger">断开</el-button>
          </el-form-item>
        </el-form>
        <br />
        <div>
        </div>
      </div>
    </template>

  </div>
</template>

<script>
// @ is an alias to /src

export default {
  name: 'chat',
  data() {
    return {
      url: "ws://127.0.0.1:9000/socket/chat/people ",
      message: "",
      text_content: "",
      userSocketInfo: [{
        nick_name: "",
        type: "",
        body: "",
      }],
      ws: null,
      socketMsg: {
        msg: "",
        from: "",
        to: "",
        group: false,
        all: false,
        group_id: "",
        user_id: "",
      },
      fromUser: {
        CreatedAt: "",
        DeletedAt: "",
        ID: "",
        UpdatedAt: "",
        friends: "",
        groups: "",
        img_id: "",
        img_http: "",
        name: "",
        nick_name: "",
        password: "",
        phone: "",
        sex: "",
        text: "",
        user_id: "",
        username: "",
      },
      toUser: {
        CreatedAt: "",
        DeletedAt: "",
        ID: "",
        UpdatedAt: "",
        friends: "",
        groups: "",
        img_id: "",
        img_http: "",
        name: "",
        nick_name: "",
        password: "",
        phone: "",
        sex: "",
        text: "",
        user_id: "",
        username: "",
      }
    };
  },
  created() {
    this.getParam()
    //获得用户信息
    this.getUserInfoF()
    this.getUserInfoT()
  },
  destroyed() {
    this.exit()
  },
  methods: {
    initWebsocket() {
      let that = this
      this.ws = new WebSocket(this.url);
      const self = this;
      this.ws.onopen = function (event) {
        // self.text_content = self.text_content + "已经打开连接!" + "\n";
      };
      this.ws.onmessage = function (event) {
        let sign = event.data.split(":")
        if (sign.length !== 0 && sign[0] === "socket") {
          //登录成功;1;  -- 发送失败 0
          let msgType = sign[1].split(";")
          if (msgType[2] === "0") {
            that.$message.error(msgType[0])
            that.userSocketInfo.pop()
          } else {
            that.$message({
              message: msgType[0],
              type: "success",
            });
          }
        } else {
          let msg = { nick_name: that.socketMsg.to, type: "left", body: event.data }
          that.userSocketInfo.push(msg)
        }
      };
      this.ws.onclose = function (event) {
        // self.text_content = self.text_content + "已经关闭连接!" + "\n";
      };
    },
    exit() {
      if (this.ws) {
        this.ws.close();
        this.ws = null;
      }
    },
    send() {
      let that = this
      let send = { nick_name: that.socketMsg.from, type: "right", body: that.socketMsg.msg }
      that.userSocketInfo.push(send)
      if (this.ws) {
        // console.log(this.socketMsg)
        this.ws.send(JSON.stringify(this.socketMsg));
        that.userSocketInfo.push(send)
      } else {
        // alert("未连接到服务器");
      }
    },
    //获得router内容
    getParam() {
      this.socketMsg.from = this.$route.params.form
      this.socketMsg.to = this.$route.params.to
      this.socketMsg.user_id = this.socketMsg.from
    },
    //查看个人信息
    getUserInfoF() {
      let token = localStorage.getItem("token")
      let that = this
      this.$axios({
        headers: {
          'Content-Type': 'multipart/form-data',
          "Authorization": "Bearer " + token
        },
        method: 'get',
        url: '/user/info/user_id?user_id=' + this.socketMsg.from,
      }).then((res) => {
        let result = res.data
        if (result.code === 1000) {
          that.fromUser = result.data
        }
      })
    },
    getUserInfoT() {
      let token = localStorage.getItem("token")
      let that = this
      this.$axios({
        headers: {
          'Content-Type': 'multipart/form-data',
          "Authorization": "Bearer " + token
        },
        method: 'get',
        url: '/user/info/user_id?user_id=' + this.socketMsg.to,
      }).then((res) => {
        let result = res.data
        if (result.code === 1000) {
          that.toUser = result.data
        }
      })
    },
    load() {
      console.log(1)
    }
  },
}
</script>
<style>
.right {
  text-align: right;
}

.left {
  text-align: left;
}

.box-card {
  width: 80%;
}

.flex_column {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.flex_row {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

/*--*/
.message {
  position: relative;
  display: flex;
  width: 100%;
  margin: 5px 0;
}

.message p {
  max-width: 70%;
  padding: 10px;
  font-size: 14px;
  float: right;
  margin-right: 10px;
  position: relative;
  margin-top: 8px;
  background: #A3C3F6;
  text-align: left;
}

.message p::before {
  position: absolute;
  left: -8px;
  top: 8px;
  content: '';
  border-right: 10px solid #FFF;
  border-top: 8px solid transparent;
  border-bottom: 8px solid transparent;
  background: linear-gradient(135deg, #dcf8c6 0%, #dcf8c6 50%, transparent 50%, transparent);
}

.message p span {
  display: block;
  margin-top: 5px;
  font-size: 0.85em;
  opacity: 0.5;
}

.my_message {
  justify-content: flex-end;
}

.frnd_message {
  justify-content: flex-start;
}

.frnd_message p {
  background: #38C0F1;
  text-align: left;
}

.message.frnd_message p::before {
  content: '';
  position: absolute;
  top: 0;
  left: -12px;
  width: 20px;
  background: linear-gradient(225deg, #38C0F1 0%, #38C0F1 50%, transparent 50%, transparent);
}</style>
